/**
 * 02/dic/2011 - fabio.melillo@gmail.com
 */
package sbc;


import it.unipr.ce.dsg.s2p.message.BasicMessage;
import it.unipr.ce.dsg.s2p.message.Payload;
import it.unipr.ce.dsg.s2p.org.json.JSONObject;
import it.unipr.ce.dsg.s2p.peer.Peer;
import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.TimeZone;

import org.zoolu.sip.message.Message;
import org.zoolu.sip.provider.SipProvider;

/**
 * @author fabio
 *
 */
public class CustomServer extends Peer {
	
	private static final String KEY = String.valueOf(GregorianCalendar.getInstance().getTimeInMillis());
	private static CustomServer me=null;
	private long expiry=1000*60; //1 minuto
	private final String[] timezone=TimeZone.getAvailableIDs(0);
	
	private CustomServer(String pathConfig, String key, String peerName,
			int peerPort) {
		super(pathConfig, key, peerName, peerPort);
	}
	
	public static CustomServer getInstance() {
		if (me==null){
			int peerPort=2222;
			String name="superPeer";
			me = new CustomServer(null, KEY, name, peerPort);
			System.out.println("Port:"+peerPort);
		}
		return me;
	}
	
	
	
	@Override
	public void onReceivedMessage(SipProvider sipPvd, Message sipMsg) {
		super.onReceivedMessage(sipPvd, sipMsg);
		System.out.println(sipPvd.toString());
		String address=sipMsg.getFromHeader().getNameAddress().toString();
		System.out.println(address+"\n");
		System.out.println(sipMsg.toString());
		String ip=sipMsg.getRemoteAddress().toString();
		int port=sipMsg.getRemotePort();
		System.out.println("[LETTO DAI PARAMETRI] remote address="+ip);
		System.out.println("[LETTO DAI PARAMETRI] remote port="+port);
		String sipAddress=sipMsg.getFromHeader().getNameAddress().getAddress().toString();
		String name=sipAddress.substring(4, sipAddress.indexOf("@"));
		System.out.println("[LETTO DAI PARAMETRI] remote name="+name);
		System.out.println("\nTento la risposta");
		
		HashMap<String, String> map=new HashMap<String, String>();
		map.put("TUO NOME", name);
		map.put("TUO IP", ip);
		map.put("TUA PORTA", String.valueOf(port));
		Address senderAddress=new Address(name,ip,port);
		BasicMessage bmsg=new BasicMessage();
		bmsg.setPayload(new Payload(map));
		this.send(senderAddress, bmsg);
		System.out.println("sent to-> "+senderAddress.toString());
//		Address sAddress=new Address("rcost2", "193.206.108.129", 46928);
//		this.send(sAddress, bmsg);
//		System.out.println("Static - sent to->"+sAddress.toString());
	}

	@Override
	protected void onDeliveryMsgFailure(String arg0, Address arg1, String arg2) {
		System.out.println("MSG Failure");
	}

	@Override
	protected void onDeliveryMsgSuccess(String arg0, Address arg1, String arg2) {
		System.out.println("MSG Success");
	}
	
	@Override
	protected void onReceivedJSONMsg(JSONObject jsonMsg, Address sender) {
		super.onReceivedJSONMsg(jsonMsg, sender);
	}

	
}
